package com.monitor.ui;

import com.monitor.control.TimeController;
import com.monitor.control.TimeRange;
import com.monitor.network.ProxyDetector;

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.time.DayOfWeek;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 控制中心面板，包含上网时间控制和代理阻断功能
 */
public class ControlPanel extends JPanel {
    private static final Color MAIN_COLOR = new Color(0, 120, 215);
    private static final String[] DAYS = {"时间/星期", "周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    private static final String[] HOURS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
                                        "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};

    private TimeController timeController;
    private ProxyDetector proxyDetector;
    private JPanel[][] timeCells;
    private boolean[][] timeSelections;
    private JRadioButton enabledBtn;
    private JRadioButton disabledBtn;

    public ControlPanel() {
        // 初始化控制器
        timeController = new TimeController();
        proxyDetector = new ProxyDetector();

        // 初始化时间选择数组
        timeCells = new JPanel[HOURS.length][DAYS.length - 1];
        timeSelections = new boolean[HOURS.length][DAYS.length - 1];

        // 从TimeController加载当前设置
        loadTimeSettings();

        // 设置面板
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);

        // 创建标题面板
        JPanel titlePanel = createTitlePanel("控制中心");
        add(titlePanel, BorderLayout.NORTH);

        // 创建内容面板
        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.setBackground(Color.WHITE);
        contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建选项卡面板
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("时间控制", createTimeControlPanel());
        tabbedPane.addTab("代理阻断", createProxyBlockPanel());

        contentPanel.add(tabbedPane, BorderLayout.CENTER);
        add(contentPanel, BorderLayout.CENTER);
    }

    private JPanel createTitlePanel(String title) {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(MAIN_COLOR);
        panel.setPreferredSize(new Dimension(800, 40));

        JLabel titleLabel = new JLabel(title, JLabel.CENTER);
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

        panel.add(titleLabel, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createTimeControlPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBackground(Color.WHITE);

        // 创建控制按钮面板
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        controlPanel.setBackground(Color.WHITE);

        enabledBtn = new JRadioButton("开启");
        disabledBtn = new JRadioButton("停止");

        // 设置当前状态
        enabledBtn.setSelected(timeController.isEnabled());
        disabledBtn.setSelected(!timeController.isEnabled());

        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(enabledBtn);
        btnGroup.add(disabledBtn);

        enabledBtn.addActionListener(e -> timeController.enable());
        disabledBtn.addActionListener(e -> timeController.disable());

        controlPanel.add(enabledBtn);
        controlPanel.add(disabledBtn);

        // 创建时间表格
        JPanel tablePanel = new JPanel(new GridLayout(HOURS.length + 1, DAYS.length));
        tablePanel.setBackground(Color.WHITE);
        tablePanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));

        // 添加表头
        for (String day : DAYS) {
            JLabel label = new JLabel(day, JLabel.CENTER);
            label.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
            tablePanel.add(label);
        }

        // 添加行和单元格
        for (int i = 0; i < HOURS.length; i++) {
            JLabel rowLabel = new JLabel(HOURS[i], JLabel.CENTER);
            rowLabel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
            tablePanel.add(rowLabel);

            for (int j = 0; j < DAYS.length - 1; j++) {
                final int row = i;
                final int col = j;

                JPanel cell = new JPanel();
                cell.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
                cell.setBackground(timeSelections[row][col] ? new Color(0, 200, 0) : Color.WHITE);

                cell.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        timeSelections[row][col] = !timeSelections[row][col];
                        cell.setBackground(timeSelections[row][col] ? new Color(0, 200, 0) : Color.WHITE);
                        updateTimeController();
                    }
                });

                timeCells[i][j] = cell;
                tablePanel.add(cell);
            }
        }

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBackground(Color.WHITE);

        JButton applyButton = new JButton("应用");
        JButton resetButton = new JButton("重置");

        applyButton.addActionListener(e -> updateTimeController());
        resetButton.addActionListener(e -> resetTimeSelections());

        buttonPanel.add(resetButton);
        buttonPanel.add(applyButton);

        // 添加说明文本
        JTextArea descArea = new JTextArea("设置每日允许上网的时间段，支持一周7天灵活设置，禁网前5分钟会预警。\n" +
                "绿色表示允许上网的时间段，白色表示禁止上网的时间段。\n" +
                "点击单元格可以切换状态。");
        descArea.setEditable(false);
        descArea.setLineWrap(true);
        descArea.setWrapStyleWord(true);
        descArea.setBackground(panel.getBackground());
        descArea.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));

        panel.add(descArea, BorderLayout.NORTH);
        panel.add(controlPanel, BorderLayout.WEST);
        panel.add(tablePanel, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    private JPanel createProxyBlockPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBackground(Color.WHITE);
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建控制按钮面板
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        controlPanel.setBackground(Color.WHITE);

        JRadioButton enabledBtn = new JRadioButton("开启");
        JRadioButton disabledBtn = new JRadioButton("停止");

        // 设置当前状态
        enabledBtn.setSelected(proxyDetector.isEnabled());
        disabledBtn.setSelected(!proxyDetector.isEnabled());

        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(enabledBtn);
        btnGroup.add(disabledBtn);

        enabledBtn.addActionListener(e -> proxyDetector.enable());
        disabledBtn.addActionListener(e -> proxyDetector.disable());

        controlPanel.add(enabledBtn);
        controlPanel.add(disabledBtn);

        // 创建代理进程列表
        DefaultListModel<String> proxyModel = new DefaultListModel<>();
        for (String process : proxyDetector.getKnownProxyProcesses()) {
            proxyModel.addElement(process);
        }

        JList<String> proxyList = new JList<>(proxyModel);
        JScrollPane listScroll = new JScrollPane(proxyList);
        listScroll.setBorder(BorderFactory.createTitledBorder("已知代理软件列表"));

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBackground(Color.WHITE);

        JButton addButton = new JButton("添加");
        JButton removeButton = new JButton("删除");
        JButton detectButton = new JButton("检测代理");
        JButton blockButton = new JButton("阻断代理");

        addButton.addActionListener(e -> {
            String process = JOptionPane.showInputDialog(panel, "请输入代理软件进程名称：");
            if (process != null && !process.trim().isEmpty()) {
                proxyDetector.addKnownProxyProcess(process.trim());
                proxyModel.addElement(process.trim());
            }
        });

        removeButton.addActionListener(e -> {
            int selectedIndex = proxyList.getSelectedIndex();
            if (selectedIndex != -1) {
                proxyModel.remove(selectedIndex);
            }
        });

        detectButton.addActionListener(e -> {
            boolean detected = proxyDetector.isProxyInUse();
            JOptionPane.showMessageDialog(panel,
                    detected ? "检测到代理服务器正在使用！" : "未检测到代理服务器。",
                    "代理检测结果",
                    detected ? JOptionPane.WARNING_MESSAGE : JOptionPane.INFORMATION_MESSAGE);
        });

        blockButton.addActionListener(e -> {
            boolean success = proxyDetector.blockProxyConnection();
            JOptionPane.showMessageDialog(panel,
                    success ? "已成功阻断代理连接！" : "阻断代理连接失败或未检测到代理。",
                    "阻断结果",
                    JOptionPane.INFORMATION_MESSAGE);
        });

        buttonPanel.add(addButton);
        buttonPanel.add(removeButton);
        buttonPanel.add(detectButton);
        buttonPanel.add(blockButton);

        // 添加说明文本
        JTextArea descArea = new JTextArea("代理阻断功能可以禁止用户通过代理服务器或匿名软件绕过过滤。\n" +
                "系统会自动检测和阻止常见的代理软件，您也可以手动添加代理软件进程名称。");
        descArea.setEditable(false);
        descArea.setLineWrap(true);
        descArea.setWrapStyleWord(true);
        descArea.setBackground(panel.getBackground());
        descArea.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));

        panel.add(descArea, BorderLayout.NORTH);
        panel.add(controlPanel, BorderLayout.WEST);
        panel.add(listScroll, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    /**
     * 从TimeController加载当前时间设置
     */
    private void loadTimeSettings() {
        // 初始化选择数组
        for (int i = 0; i < HOURS.length; i++) {
            for (int j = 0; j < DAYS.length - 1; j++) {
                timeSelections[i][j] = false;
            }
        }

        // 获取每天的允许时间范围
        for (int dayIndex = 0; dayIndex < 7; dayIndex++) {
            DayOfWeek day = DayOfWeek.of(dayIndex == 0 ? 7 : dayIndex); // 调整星期日的索引
            TimeRange[] ranges = timeController.getAllowedTimeRanges(day);

            if (ranges != null) {
                for (TimeRange range : ranges) {
                    int startHour = range.getStartTime().getHour();
                    int endHour = range.getEndTime().getHour();

                    // 如果结束时间的分钟不为0，则包括结束小时
                    if (range.getEndTime().getMinute() > 0) {
                        endHour++;
                    }

                    // 标记允许的时间段
                    for (int hour = startHour; hour < endHour; hour++) {
                        if (hour >= 0 && hour < 24) {
                            timeSelections[hour][dayIndex] = true;
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据当前选择更新TimeController
     */
    private void updateTimeController() {
        // 为每天创建时间范围
        for (int dayIndex = 0; dayIndex < 7; dayIndex++) {
            DayOfWeek day = DayOfWeek.of(dayIndex == 0 ? 7 : dayIndex); // 调整星期日的索引
            List<TimeRange> ranges = new ArrayList<>();

            int startHour = -1;

            // 查找连续的允许时间段
            for (int hour = 0; hour <= 24; hour++) {
                boolean isAllowed = hour < 24 && timeSelections[hour][dayIndex];

                if (isAllowed && startHour == -1) {
                    // 开始新的时间段
                    startHour = hour;
                } else if (!isAllowed && startHour != -1) {
                    // 结束当前时间段
                    ranges.add(new TimeRange(
                            LocalTime.of(startHour, 0),
                            LocalTime.of(hour, 0)
                    ));
                    startHour = -1;
                }
            }

            // 设置该天的时间范围
            timeController.setAllowedTimeRanges(day, ranges.toArray(new TimeRange[0]));
        }
    }

    /**
     * 重置时间选择
     */
    private void resetTimeSelections() {
        // 重置TimeController到默认设置
        timeController = new TimeController();

        // 重新加载设置到UI
        loadTimeSettings();

        // 更新UI
        for (int i = 0; i < HOURS.length; i++) {
            for (int j = 0; j < DAYS.length - 1; j++) {
                timeCells[i][j].setBackground(timeSelections[i][j] ? new Color(0, 200, 0) : Color.WHITE);
            }
        }
    }

    /**
     * 获取时间控制器实例
     */
    public TimeController getTimeController() {
        return timeController;
    }

    /**
     * 获取代理检测器实例
     */
    public ProxyDetector getProxyDetector() {
        return proxyDetector;
    }
}
